<template>
  <el-cascader
    :options="cities"
    @active-item-change="handleItemChange"
    @change="change"
    :value="initValue"
    :props="props"
  ></el-cascader>
</template>

<script lang="ts">
  import { Vue, Component, Prop } from 'vue-property-decorator'

  @Component
  export default class Address extends Vue {
    initValue = []
    cities = []
    props = {
      value: 'id',
      label: 'name',
      children: 'cities'
    }

    async handleItemChange (ids) {
      if (ids.length === 0) {
        this.cities = await this.getArea('0', false)
      } else if (ids.length === 1) {
        for (let i = 0; i < this.cities.length; i++) {
          if (this.cities[i].id === ids[0]) {
            this.cities[i].cities = await this.getArea(ids[0], false)
          }
        }
      } else if (ids.length === 2) {
        for (let i = 0; i < this.cities.length; i++) {
          if (this.cities[i].id === ids[0]) {
            for (let j = 0; j < this.cities[i].cities.length; j++) {
              if (this.cities[i].cities[j].id === ids[1]) {
                this.cities[i].cities[j].cities = await this.getArea(ids[1], true)
              }
            }
          }
        }
      }
    }

    async getArea (parentId, isEnd) {
      let res: AjaxResponse = await this.$axios.get(`g/gateway/area/${parentId}/areas`)
      if (!isEnd) {
        res.data.forEach(v => v.cities = [])
      }
      return res.data
    }

    mounted () {
      this.handleItemChange([])
    }

    change (areas) {
      this.$emit('input', areas)
    }

    async init (initValue) {
      this.initValue = initValue
      setTimeout(async () => {
        for (let i = 0; i < this.cities.length; i++) {
          if (this.cities[i].id === initValue[0]) {
            this.cities[i].cities = await this.getArea(initValue[0], false)
            for (let j = 0; j < this.cities[i].cities.length; j++) {
              if (this.cities[i].cities[j].id === initValue[1]) {
                this.cities[i].cities[j].cities = await this.getArea(initValue[1], true)
              }
            }
          }
        }
      }, 400)
      this.$emit('input', initValue)

    }
  }
</script>

<style lang="less" scoped>
  .el-cascader {
    width: 300px;
  }
</style>
